﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SoftwareMonkeys.LogClimber.Entities;
using System.IO;

namespace SoftwareMonkeys.LogClimber.Business
{
    public class StackTraceLoader
    {
        public string Load(LogProject project, Entry entry)
        {
            if (entry.Log == null)
                throw new ArgumentNullException("entry.Log");

            if (entry.Log.DateStamp == String.Empty)
                throw new ArithmeticException("entry.Log.DateStamp");

            string logDirectory = project.WwwDirectory + Path.DirectorySeparatorChar
                + "App_Data" + Path.DirectorySeparatorChar
                + "Logs" + Path.DirectorySeparatorChar
                + entry.Log.DateStamp;

            return Load(logDirectory, entry.ID);
        }

        public string Load(string logDirectoryPath, Entry entry)
        {
        	return Load(logDirectoryPath, entry.ID);
        }
        
        public string Load(string logDirectoryPath, Guid entryID)
        {
            string filePath = GetStackTraceFilePath(logDirectoryPath, entryID);
            
            string stackTrace = GetStackTrace(filePath);

            stackTrace = stackTrace.Replace("\n\r", "\n").Replace("\n\n", "\n");

            return stackTrace;
        }

        public string GetStackTraceFilePath(string logDirectoryPath, Guid entryID)
        {
            string path = logDirectoryPath + Path.DirectorySeparatorChar
                + "StackTrace" + Path.DirectorySeparatorChar
                + entryID.ToString() + ".trace";

            return path;
        }

        public string GetStackTrace(string filePath)
        {
            if (!File.Exists(filePath))
            {
                return String.Empty;
            }
            else
            {
                string fileContent = String.Empty;
                using (StreamReader reader = new StreamReader(File.OpenRead(filePath)))
                {
                    fileContent = reader.ReadToEnd();
                }
                return fileContent;
            }
        }

    }
}
